package araxy.blog.controller;

import araxy.blog.entity.Token;
import araxy.blog.exception.LoginException;
import araxy.blog.exception.TokenException;
import araxy.blog.service.TokenService;
import araxy.blog.service.UserService;
import araxy.blog.utils.JsonUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@RestController
public class LoginController {

    @Resource
    UserService userService;

    @Resource
    TokenService tokenService;

    @PostMapping("/password-login")
    public Object passwordAuth(String account,String passwd) throws JsonProcessingException {
        Object obj = userService.passwordAuth(account,passwd);
        return setToken(obj);
    }

    private Object setToken(Object obj) {
        if ( !(obj instanceof Map) ) {
            return obj;
        }
        Map<String,Object> map = (Map<String, Object>) obj;
        if ( !map.containsKey("token")) {
            return map;
        }
        Token t = (Token) map.get("token");
        if (!tokenService.insertToken(t)) {
            map.remove("token");
            return map;
        }
        map.put("token",t.getSignature());
        return map;
    }

    @PostMapping("/token-login")
    public Object tokenAuth(HttpServletRequest request) throws JsonProcessingException {
        Cookie[] cookies = request.getCookies();
        String signature = null;
        for ( Cookie cookie : cookies ) {
            if ("token".equals(cookie.getName())) {
                signature = cookie.getValue();
            }
        }
        if (signature == null) {
            throw new TokenException("cookies中没有token");
        }
        String token = tokenService.getTokenBySignature(signature);
        Object obj = userService.tokenAuth(token);
        return setToken(obj);
    }

}
